package copyengine.notification {
    import copyengine.log.CELog;
    import copyengine.utils.GeneralUtils;

    import flash.utils.Dictionary;

    /**
 * <b>一个比较简单的观察者模式</b></br>
 * </br>将字符串和回调函数直接绑定在一起
 * </br><li>Ex: CENotificationFacade.mInstance.register("onPlayerProfileVoChange",onChangeCallBack);
 * </br>不像PureMVC那样,需要监听消息还要写一个Mediator
 */
public final class CENotificationFacade {
    private static var mInstance:CENotificationFacade;

    public static function get instance():CENotificationFacade {
        if (mInstance == null) {
            mInstance = new CENotificationFacade();
        }
        return mInstance;
    }

    private var mAllActiveNotificationDic:Dictionary;

    public function CENotificationFacade() {
        mAllActiveNotificationDic = new Dictionary();
    }

    public function register(_notification:String, _callBack:Function):void {
        var holdCallBackVector:Vector.<Function>;
        if (mAllActiveNotificationDic[_notification] == null) {
            holdCallBackVector = new Vector.<Function>();
            mAllActiveNotificationDic[_notification] = holdCallBackVector;
        }
        else {
            holdCallBackVector = mAllActiveNotificationDic[_notification];
        }
        holdCallBackVector.push(_callBack);
    }

    public function unRegister(_notification:String, _callBack:Function):void {
        if (mAllActiveNotificationDic[_notification] != null) {
            var holdCallBackVector:Vector.<Function> = mAllActiveNotificationDic[_notification];
            GeneralUtils.removeElementFromArrayOrVector(_callBack, holdCallBackVector);
            if (holdCallBackVector.length == 0) {
                mAllActiveNotificationDic[_notification] = null;
                delete mAllActiveNotificationDic[_notification];
            }
        }
    }

    public function sendNotification(_notification:String, _notificationArg:Object = null):void {
        var holdCallBackVector:Vector.<Function> = mAllActiveNotificationDic[_notification];
        if (holdCallBackVector != null) {
            var tempVector:Vector.<Function> = new Vector.<Function>();

            //首先要将所有函数潜拷贝到一个临时Vector里面
            //1·先拷贝一份是怕在发送期间调用了unRegister方法,删除了callback,导致for each函数少loop
            //2·采用临时变量是防止在sendNotification期间的回调函数又导致触发了sendNotification,产生了递归
            for each (var holdCallBack:Function in holdCallBackVector) {
                tempVector.push(holdCallBack);
            }

            for each (var callBack:Function in tempVector) {
                if (callBack.length == 1) {
                    callBack(_notificationArg);
                }
                else if (callBack.length == 0) {
                    callBack();
                }
                else {
                    CELog.err("unknown CENotification call back arg num with : " + callBack.length);
                }
            }
            tempVector = null;
        }
    }

}
}
